package com.example.sjc715.main.ui.home

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.commonlibrary.mvi.BaseViewModel
import com.example.sjc715.login.LoginIntent
import com.example.sjc715.login.LoginState
import kotlinx.coroutines.flow.consumeAsFlow
import kotlinx.coroutines.launch

class HomeViewModel : BaseViewModel<HomeIntent,HomeState>() {
    init {
        viewModelScope.launch {
            intent.consumeAsFlow().collect{
                when(it){
                    is HomeIntent.loadType->getType()
                    is HomeIntent.loadVideo->getVideo(it.id,it.page,it.size)
                }
            }
        }
    }

    private suspend fun getVideo(id: String, page: Int, size: Int) {
        val s = try {
            val res = service.getSimpleVideo(id,page, size)
            if(res.code == 0){
                HomeState.VideoSuccess(res)
            }else{
                HomeState.Failure(res.msg)
            }
        }catch (e:Exception){
            HomeState.Failure(e.message?:"")
        }
        state.postValue(s)
    }

    private suspend fun getType() {
        val s = try {
            val res = service.getSimpleType()
            if(res.code == 0){
                HomeState.TypeSuccess(res)
            }else{
                HomeState.Failure(res.msg)
            }
        }catch (e:Exception){
            HomeState.Failure(e.message?:"")
        }
        state.postValue(s)
    }
}